package com.myh.testlogin.controller;


import com.myh.testlogin.common.result.Result;
import com.myh.testlogin.common.staticnum.StaticConstant;
import com.myh.testlogin.entity.User;
import com.myh.testlogin.service.impl.UserServiceImpl;
import com.myh.testlogin.util.JwtUtils;
import com.myh.testlogin.util.RedisUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 作者：莫耀华
 * @since 2020-09-16
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 过期时间 秒  tokenh过期时间
     */
    @Value("${myh.jwt.expire}")
    private long expire;
    /**
     * 登录接口
     *
     * @param user 用户对象
     *             username 用户名
     *             password 密码
     * @return
     */
    @PostMapping("/login")
    public Result login(@Validated @RequestBody User user,HttpServletRequest request) {
//        Enumeration<String> headerNames = request.getHeaderNames();
//        while (headerNames.hasMoreElements()){
//            String s = headerNames.nextElement();
//            System.out.println("s="+s+" "+request.getHeader(s));
//        }
//        System.out.println(request.getHeader("Authorization")+"token");
        HashMap<String, Object> msgMap = new HashMap<>();
        User userDb = userService.loginByUserName(user.getUsername());
        Assert.notNull(userDb, "用户不存在");
        if (userDb != null) {
            //比较密码
            if (Strings.isEmpty(user.getPassword())) {
                msgMap.put("password", "密码不能为空");
                return Result.error(StaticConstant.CODE_400,"密码不能为空").put("data", null);
            } else {
                //密码不为空   判断密码是否正确
                if (user.getPassword().equals(userDb.getPassword())) {
                    //登录成功 将token和用户id一起报错到redis中  时间读取配置文件
                    //返回token
                    HashMap<String, String> usergMap = new HashMap<>();
                    usergMap.put("id", String.valueOf(userDb.getId()));
                    usergMap.put("nickname", String.valueOf(userDb.getNickname()));
                    usergMap.put("username", String.valueOf(userDb.getUsername()));
                    String token = (String) redisUtils.get("uid" + userDb.getId());
                    System.out.println("token=="+token);
                    if(token==null){
                        //从redis取出token
                        token = jwtUtils.getToken(usergMap);
                        redisUtils.set("uid" + userDb.getId(), token,expire);
                    }
                    //如果redis的token不为空
                    return Result.ok(StaticConstant.CODE_200, "登录成功").put("token", token).put("data", usergMap);
                } else {
                    //密码错误
                    msgMap.put("password", "密码错误");
                    return Result.error(StaticConstant.CODE_201,"密码错误").put("data", msgMap);
                }
            }
        }//用户不存在
        return Result.error(StaticConstant.CODE_400,"用户不存在").put("data", null);
    }

    @GetMapping("/test")
    public String hello(){
        return  "hello";
    }

    /**
     * 获取token 的用户的id
     * @param user  新密码
     * @param request
     * @return
     */
    @PutMapping("/updatePwdById")
    public Result updatePwdByUId(@RequestBody  User user,HttpServletRequest request){
        System.out.println("user.getPassword()="+user.getPassword());
        String token = request.getHeader("Authorization");
        //用户id
        int id = Integer.parseInt(jwtUtils.getUsername(token, "id"));
        int updateCount = userService.updatePwdById(id, user.getPassword());
        if(updateCount>0){
            User userDb=userService.getById(id);
            userDb.setPassword(null);
            //更新成功
            return Result.ok(StaticConstant.CODE_200,"密码修改成功").put("data",userDb);
        }
        //根据用户id修改密码
        return  Result.ok(StaticConstant.CODE_201,"密码修改失败").put("data",null);
    }
}
